using Mathmall.Administration.Data;
using Mathmall.Administration.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;

namespace Mathmall.Administration.Mapper;

public class RoleMenuMapper : BaseMapper
{
    public RoleMenuMapper(AdministrationContext context) : base(context)
    {
    }

    /// <summary>
    /// 查询角色已有的权限
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task<List<RoleMenu>> QueryRolePossessedMenuIds(int roleId)
    {
        return await _context.RoleMenu.Where(roleMenu => roleMenu.RoleId == roleId).ToListAsync();
    }

    /// <summary>
    /// 为角色添加权限
    /// </summary>
    /// <param name="roleMenus"></param>
    /// <returns></returns>
    public async Task<int> CreateRoleMenu(List<RoleMenu> roleMenus)
    {
        // 1.删除角色的所有角色
        await _context.RoleMenu.Where(roleMenu => roleMenu.RoleId == roleMenus[0].RoleId).ExecuteDeleteAsync();
        // 2.为角色添加权限
        foreach (RoleMenu roleMenu in roleMenus)
        {
            _context.RoleMenu.Add(roleMenu);
        }

        return await _context.SaveChangesAsync();
    }

    /// <summary>
    /// 删除角色对应的权限
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task<int> DeleteRoleMenu(int roleId)
    {
        return await _context.RoleMenu.Where(roleMenu => roleMenu.RoleId == roleId).ExecuteDeleteAsync();
    }
}